from . import db  # 从 models/__init__.py 导入 db
from datetime import datetime

# 多对多关系表
user_roles = db.Table('user_roles',
    db.Column('user_id', db.Integer, db.ForeignKey('admin_user.id')),
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id'))
)

role_permissions = db.Table('role_permissions',
    db.Column('role_id', db.Integer, db.ForeignKey('roles.id')),
    db.Column('permission_id', db.Integer, db.ForeignKey('permissions.id'))
)

user_resources = db.Table('user_resources',
    db.Column('user_id', db.Integer, db.ForeignKey('admin_user.id')),
    db.Column('resource_id', db.Integer, db.ForeignKey('resources.id'))
)

class AdminUser(db.Model):
    """用户表（admin_user）"""
    __tablename__ = 'admin_user'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    mobile = db.Column(db.String(20), unique=True, nullable=False)
    roleid = db.Column(db.Integer, db.ForeignKey('roles.id'))  # 角色ID
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 多对多关系：用户和角色
    roles = db.relationship('Role', secondary=user_roles, backref=db.backref('users', lazy='dynamic'))
    
    # 多对多关系：用户和资源（ACL权限）
    resources = db.relationship('Resource', secondary=user_resources, backref=db.backref('users', lazy='dynamic'))
    
    def __repr__(self):
        return f"<AdminUser {self.name}>"

class Role(db.Model):
    """角色表"""
    __tablename__ = 'roles'
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True, nullable=False)
    description = db.Column(db.Text)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 多对多关系：角色和权限
    permissions = db.relationship('Permission', secondary=role_permissions, backref=db.backref('roles', lazy='dynamic'))
    
    def __repr__(self):
        return f"<Role {self.name}>"

class Resource(db.Model):
    """资源表"""
    __tablename__ = 'resources'
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    pid = db.Column(db.Integer, db.ForeignKey('resources.id'), nullable=True)  # 父级资源ID
    level = db.Column(db.Integer, default=1)  # 层级
    topid = db.Column(db.Integer, default=0)  # 顶级ID
    url = db.Column(db.String(200))  # 资源URL
    icon = db.Column(db.String(100))  # 图标
    sort = db.Column(db.Integer, default=0)  # 排序
    status = db.Column(db.Boolean, default=True)  # 状态
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f"<Resource {self.name}>"

class Permission(db.Model):
    """权限表"""
    __tablename__ = 'permissions'
    __table_args__ = {'extend_existing': True}
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), nullable=False)
    resource_id = db.Column(db.Integer, db.ForeignKey('resources.id'))
    action = db.Column(db.String(32), nullable=False)  # 操作类型：read, write, delete
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def __repr__(self):
        return f"<Permission {self.name}>"
